package com.whoimi.admin.service.impl;

import com.whoimi.admin.entity.CurrentUserDTO;
import com.whoimi.admin.entity.Menu;
import com.whoimi.admin.entity.User;
import com.whoimi.admin.repository.MenuRepository;
import com.whoimi.admin.repository.UserRepository;
import com.whoimi.admin.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

/**
 * @author whoimi
 * @since 2025-07-25
 **/
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserRepository userRepository;
    @Resource
    private MenuRepository menuRepository;

    @Override
    public CurrentUserDTO getCurrentUserInfo(String username) {


        // 获取登录用户基础信息
        User user = userRepository.findByUsername(username).orElseThrow(() -> new RuntimeException("用户不存在"));
        // entity->VO
        CurrentUserDTO target = new CurrentUserDTO();
        BeanUtils.copyProperties(user, target);
        target.setUserId(user.getId());
        target.setRoles(Collections.singleton("ADMIN"));

        Iterable<Menu> byType = menuRepository.findByType("4");
        Set<String> perms = StreamSupport.stream(byType.spliterator(), false)
                .map(Menu::getPerm)
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());

        target.setPerms(perms);
        // 用户角色集合
//        Set<String> roles = SecurityUtils.getRoles();
//        userInfoVO.setRoles(roles);

        // 用户权限集合
//        if (CollectionUtil.isNotEmpty(roles)) {
//            Set<String> perms = permissionService.getRolePermsFormCache(roles);
//            userInfoVO.setPerms(perms);
//        }
        return target;
    }

    @Override
    public void deleteAllById(String ids) {
        if (StringUtils.hasLength(ids)) {
            List<Long> idList = Arrays.stream(ids.split(",")).map(Long::parseLong).toList();
            if (idList.size() == 1) {
                userRepository.deleteById(idList.get(0));
            } else {
                userRepository.deleteAllById(idList);
            }
        }
    }
}
